import logging
import re

from django.contrib.auth import login
from django.http.response import HttpResponse
from django.shortcuts import render
from django_redis import get_redis_connection
from rest_framework.response import Response
from rest_framework.views import APIView

from captcha.captcha import captcha
from celery_tasks.sms.tasks import send_celery_code

from demo.models import User



# Create your views here.



class UsernameView(APIView):
    def get(self,request,name):
        user = User.objects.filter(username=name).count()
        return Response({'code':0,'user':user})
class MobileView(APIView):
    def get(self,request,mobile):
        mobile = User.objects.filter(mobile=mobile).count()
        return Response({'code':0,'mobile':mobile})
class ImageView(APIView):
    def get(self,request,image_code_id):
        image_code,image =captcha.generate_captcha()
        a1 = get_redis_connection()
        a1.set(image_code_id,image_code,60)
        return HttpResponse(image,content_type='image/jpeg')

class Send(APIView):
    def get(self,request,mobile):
        if re.match(r'^[3-9],\d{9}',mobile):
            return Response({'messsg':'手机号码不合规范'},status=400)
        a1 = get_redis_connection()
        a2=a1.get(mobile)
        if a2 is not None:
            return Response({'code':400,'message':'验证码已存在，请勿重复发送'},status=400)
        image_code = request.GET.get('image_code')
        image_code_id = request.GET.get('image_code_id')
        b1 = get_redis_connection()
        b2=b1.get(image_code_id)
        if b2 is None:
            return Response({'code':400,'message':'图片验证码错误'},status=400)
        if b2.decode().lower()!= image_code.lower():
            return Response({'code':400,'message':'验证码错误，请重新输入'},status=400)
        from random import randint
        code = str(randint(1000,9999))
        send_celery_code.delay(mobile,code)
        b2  =get_redis_connection()
        b2.setex(mobile,120,code)

        return Response({'code':0,'errmsg':'ok'})
class RegisterView(APIView):
    def post(self,request):
        username = request.data.get('username')
        password = request.data.get('password')
        password2 = request.data.get('password2')
        mobile = request.data.get('mobile')
        sms_code = request.data.get('sms_code')
        if not all((username,password,password2,sms_code)):
            return Response({'code':400,'errmsg':'参数不全'})
        if not re.match(r'^[a-zA-Z0-9_]{5,20}$',username):
            return Response({'code':400,'errmsg':'用户名格式错误'},status=400)
        if re.match(r'[3-9]\d{9}',mobile):
            return Response({'code':400,'errmsg':'手机号格式错误'},status=400)
        if password != password2:
            return Response({'code':400,'errmsg':'两次密码不一致'},status=400)
        b3 = get_redis_connection()
        aa=b3.get(mobile)
        if aa is None:
            return Response({'code':400,'errmsg':'手机验证码错误'},status=400)
        if aa.decode()!= sms_code:
            return Response({'code':400,'errmsg':'验证码错误'},status=400)
        try:
            user = User.objects.create_user(
                username=username,
                password=password,
                mobile=mobile
            )
        except:
            return Response({'code':400,'errmsg':'账号或密码错误'},status=400)
        login(request,user)
        a1 = Response({'code':0,'errmsg':'ok'})
        a1.set_cookie('username',user.username,7*24*3600)
        return a1

